<?php

namespace App\Http\Controllers\Api;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\PaymentInfo;
use App\Models\Order;
use App\Models\Station;
use GuzzleHttp\Client;
use App\Jobs\TimeOutOrder;
use Exception;

class PaymentInfoController extends Controller
{
    // 订单支付列表
    public function create($user_id, $oauth_id, $data) {
        PaymentInfo::create([
            'user_id' => $user_id,
            'oauth_id' => $oauth_id,
            'amount' => $data->amount,
            'createTime' => $data->createTime,
            'hicardOrderNo' => $data->hicardOrderNo,
            'merchOrderNo' => $data->merchOrderNo,
            'payInfo' => $data->payInfo,
            'respCode' => $data->respCode,
            'respMsg' => $data->respMsg
        ]);
    }

    // 支付回调
    public function callback(Request $request) {
        $result = json_decode(Request::createFromGlobals()->getContent());

        if ($result->respCode == '00') {
            $order = Order::where([
                'order_id' => $result->merchOrderNo
            ])->first();
            if (!$order) return $this->failed('订单不存在', 200);
            if ($order->order_status == '1') {
                // $this->dispatch(new TimeOutOrder($order, config('app.order_timeout')));
                // 支付成功，修改订单状态
                $order->order_status = '2';
                $order->realpay = $result->amount;  // 实付金额
                $order->payment_time = date("Y-m-d H:i:s");
                $order->save();
                if ($order->order_type == '一键加油') {
                    TimeOutOrder::dispatch($order, config('app.order_timeout'));
                }

                // 微信消息模板
                $WechatCOntroller = new WechatController();
                $station = Station::where('code_id', $order->station_id)->first();
                $WechatCOntroller->send($order, $station);
                // 支付成功后，开启队列，48小时后失效
                return [
                    'respCode' => '00',
                    'respMsg' => '订单支付成功!'
                ];
                // return $this->success('订单支付成功！');
            }
        }
        return [
            'respCode' => '01',
            'respMsg' => '交易异常!'
        ];
    }

    // 查询支付信息，重新去付款
    public function query(Request $request) {
        $userAuth = Auth::guard('api')->user();
        $user_id = $userAuth->user_id;
        $paymentInfo = PaymentInfo::where([
            'respCode' => '00',
            'merchOrderNo' => $request->order_id,
            'user_id' => $user_id,
        ])->first();
        if (!$paymentInfo) {
            return $this->failed('订单不存在！', 200);
        }
        return $this->success($paymentInfo);
    }

    // 查询支付结果
    public function queryResult(Request $request) {
        $user_id = $request->user_id;
        $order_id = $request->order_id;
        
        $order = Order::where(['order_id' => $order_id, 'user_id' => $user_id])->first();
        if (!$order) return $this->failed('订单不存在', 200);
        
        $paymentInfo = PaymentInfo::where([
            'respCode' => '00',
            'merchOrderNo' => $order_id,
            'user_id' => $user_id,
        ])->first();
        $content = $this->PaymentResult($paymentInfo);
        return $this->success(['callback' => $content, 'order' => $order]);
    }

    // 支付结果接口
    public function PaymentResult($paymentInfo) {
        $client = new Client();

        $url = env('WECHAT_PAYMENT_URL').'hicardpay/order/query';
        $json = [
            "createTime" => $paymentInfo->createTime,
            "hicardMerchNo" => env('WECHAT_PAYMENT_MERCHANT_ID'),
            "hicardOrderNo" => $paymentInfo->hicardOrderNo,
            "merchOrderNo" => $paymentInfo->merchOrderNo,
            "organNo" => env('WECHAT_PAYMENT_ORGANNO'),
            "version" => "V003"
        ];

        $string = '';
        foreach($json as $key => $value) {
            $string .=  $key.'='.$value.'&';
        }
        $sign = $string.env('WECHAT_PAYMENT_SIGN');
        $json['sign'] = md5($sign);

        $response = $client->request('POST', $url, [
            'headers' => [
                'Content-Type'=>'application/json;charset=UTF-8'
            ],
            'json' => $json
        ]);
        return json_decode($response->getBody()->getContents());
    }

    // 支付信息列表
    public function list(Request $request) {
        $paymentList = PaymentInfo::orderBy('created_at', 'desc')->paginate(10);
        return $this->success($paymentList);
    }

    // 查询支付信息列表
    public function search(Request $request) {
        $merchOrderNo = $request->merchOrderNo;
        $date = $request->date;
        $paymentList = [];

        if ($merchOrderNo) {
            $paymentList = PaymentInfo::where('merchOrderNo', $merchOrderNo)->paginate(10);
        }
        if ($date) {
            $paymentList = PaymentInfo::whereDate('created_at', $date)->orderBy('created_at', 'desc')->paginate(10);
        }
        
        return $this->success($paymentList);
    }
}
